<?php

namespace App\Services;


use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Overtrue\LaravelWeChat\Facade;

/**
 * 乘客端用户相关
 * Class PassengerLoginService
 * @package App\Services
 */
class PassengerUserService extends BaseService
{


    /**
     * 根据用户ID修改用户信息
     * @param $user_id
     * @param $data
     */
    public function saveByUserId($user_id, $data)
    {
        $model = User::query()->find($user_id);

        if (isset($data['password']) && $model->password == password_hash($data['password'], PASSWORD_BCRYPT)) //密码无改动
            unset($data['password']);
        if (isset($data['password']))
            $data['password'] = password_hash($data['password'], PASSWORD_BCRYPT);

        if (isset($data['code'])) {
            $app = Facade::miniProgram();
            $session = $app->auth->session($data['code']);
            //['session_key'=> 'Yg4PiZoBWX/XGnW/xZKkxg==' ,'openid'=> 'oWLg4457OgqSURzGEBS_YxFRS5BM']
            if (isset($session['errcode']))
                return_bob($session['errmsg'], 0, 200);

            unset($data['code']);
            $data['open_id'] = $session['openid'];
        }

        foreach ($data as $key => $value) {
            if ($value === NULL)
                continue;
            $model->{$key} = $value;
        }

        return $model->save() === false ? false : $model;
    }


    /**
     * 获取用户详情
     * @param $user_id
     * @return User|User[]|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null
     */
    public function getDetail($user_id)
    {
        $select_field = [
            //头像， 昵称， 手机号
            'avatar', 'nick_name', 'phone',
        ];
        return User::query()->select($select_field)->find($user_id);
    }


    /**
     * 微信小程序授权
     * @param $code
     * @return bool|int
     * @throws \App\Exceptions\BobException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function authWxmini($code)
    {
        $app = Facade::miniProgram();
        $session = $app->auth->session($code);

        //['session_key'=> 'Yg4PiZoBWX/XGnW/xZKkxg==' ,'openid'=> 'oWLg4457OgqSURzGEBS_YxFRS5BM']
        if (isset($session['errcode']))
            return_bob($session['errmsg'], 0, 200);

        $user = User::query()->find(Auth::id());
        $user->open_id = $session['openid'];

        if ($user->save() === false)
            return_bob('操作失败', 0, 200);

        $login_service = new PassengerLoginService();
        return $login_service->respondWithToken($user);

    }


    /**
     * 设置用户Unionid
     * @param $code
     * @return int
     * @throws \App\Exceptions\BobException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function setUnionid($code)
    {

        $app = Facade::miniProgram();
        $session = $app->auth->session($code);
        if (isset($session['errcode']))
            return_bob($session['errmsg'], 0, 200);

        if (!isset($session['unionid']))
            return 0;

        if (!Auth::user()->unionid) { //不存在才更新
            User::query()->where('id', Auth::id())->update([
                'open_id' => $session['openid'],
                'unionid' => $session['unionid']
            ]);
        }

        return 1;

    }

    /**
     * 用户充值
     */
    public function RechargeBalance($balace)
    {
        //更新用户余额
        User::query()->where('id', Auth::id())->update(['balance' => DB::raw('balance +' . $balace)]);
    }

    /**
     * 钱包
     */
    public function wallet()
    {
       return  User::query()->where('id', Auth::id())->first('balance');
    }
}
